package store.lunangangster.engine.bpmn.parser;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import store.lunangangster.bpmn.converter.BpmnXmlConverter;
import store.lunangangster.bpmn.model.BpmnModel;
import store.lunangangster.bpmn.model.FlowElement;
import store.lunangangster.bpmn.model.Process;
import store.lunangangster.engine.bpmn.parser.handler.BpmnParseHandlers;
import store.lunangangster.engine.impl.entity.ProcessDefinitionEntity;
import store.lunangangster.engine.impl.entity.ResourceEntity;

public class BpmnParser {

  protected BpmnModel bpmnModel;
  protected Process currentProcess;     // 指向当前正在进行处理的Process对象
  protected FlowElement currentElement; // 指向正在进行解析的FlowElement对象
  protected ResourceEntity resourceEntity;
  protected List<ProcessDefinitionEntity> processDefinitionEntities = new ArrayList<>();

  protected BpmnParseHandlers bpmnParseHandlers;
  protected BpmnXmlConverter converter;

  protected BpmnParser(BpmnParseHandlers bpmnParseHandlers) {
    this.bpmnParseHandlers = bpmnParseHandlers;
    this.converter = new BpmnXmlConverter();
  }

  public void parse() {
    bpmnModel = converter.convert(new ByteArrayInputStream(resourceEntity.getBytes()));
    applyHandler();
  }


  private void applyHandler() {
    for (Process process : bpmnModel.getProcesses()) {
      this.setCurrentProcess(process);
      bpmnParseHandlers.handleElement(this, process);
    }
  }

  public BpmnModel getBpmnModel() {
    return bpmnModel;
  }

  public Process getCurrentProcess() {
    return currentProcess;
  }

  public void setCurrentProcess(Process currentProcess) {
    this.currentProcess = currentProcess;
  }

  public FlowElement getCurrentElement() {
    return currentElement;
  }

  public void setCurrentElement(FlowElement currentElement) {
    this.currentElement = currentElement;
  }

  public ResourceEntity getResourceEntity() {
    return resourceEntity;
  }

  public void setResourceEntity(ResourceEntity resourceEntity) {
    this.resourceEntity = resourceEntity;
  }

  public List<ProcessDefinitionEntity> getProcessDefinitionEntities() {
    return processDefinitionEntities;
  }

  public void setProcessDefinitionEntities(
      List<ProcessDefinitionEntity> processDefinitionEntities) {
    this.processDefinitionEntities = processDefinitionEntities;
  }

  public BpmnParseHandlers getBpmnParseHandlers() {
    return bpmnParseHandlers;
  }

  public void setBpmnParseHandlers(
      BpmnParseHandlers bpmnParseHandlers) {
    this.bpmnParseHandlers = bpmnParseHandlers;
  }


}
